#include "ChatFromClient.hh"
#include "XmlServerThread.hh"
#include "../World/Galaxy.hh"
#include "../World/Player.hh"
#include "../World/User.hh"
#include "../Exception.hh"

using namespace Network;
using namespace World;

spChatFromClient ChatFromClient::construct(QDomElement const& message) {

    QDomElement msg = message.firstChildElement("message");
    QDomNode msgText = msg.firstChild();

    if (!(msg.isElement() && msgText.isText()))
        throw NonFatalProtocolError(
        		"chat_client.message missing or invalid");

    return spChatFromClient(new ChatFromClient(msgText.toText().nodeValue()));
}

ChatFromClient::ChatFromClient(QString const& msg):
    msg(msg)
{}

void ChatFromClient::process_on_server(XmlServerThread& thread)
{
	spUser user = thread.get_user();
	spPlayer player = thread.get_player();

	if (!user)
		throw NonFatalProtocolError("chatfromclient invalid user");

	thread.broadcast_chat_message(msg);

}

QDomDocument ChatFromClient::to_xml() const {
    QDomDocument doc;
    QDomElement chat = doc.createElement("chat_client");
    QDomElement msgElem = doc.createElement("message");
    QDomText msgText = doc.createTextNode(msg);
    doc.appendChild(chat);
    chat.appendChild(msgElem);
    msgElem.appendChild(msgText);

    return doc;
}
